const { Admin } = require('dao'),
	security = require('lib/security'),
	utils = require('lib/utils'),
	config = require('config'),
	errors = require('error');

function* signIn({ username, password }) {
	if (!username && !password) errors.throwLackParameters();
	password = security.sign(password);
	let admin = yield Admin.findOne({ where: { username, password, deleted: false } });
	if (!admin) {
		admin = yield getConfigAdmin(username, password);
		if (!admin) errors.throwAccountOrPwdError();
	}

	yield Admin.update({ lastLoginDate: new Date }, { where: { id: admin.id } });
	return admin.get({ plain: true }); //to js object
}

/**
 * 配置文件创建用户登录
 * @param {[type]} username      [description]
 * @param {[type]} password      [description]
 * @yield {[type]} [description]
 */
function* getConfigAdmin(username, password) {
	let adminUsers = config.auth.users;
	let admin = adminUsers.find(u => u.username == username && u.password == password);
	if (!admin) return null;

	let user = yield Admin.findOne({ where: { username } });
	if (!user) { //配置用户不存在
		user = yield Admin.create({ username, password });
	} else if (user.password != password) { //配置密码与数据库密码不一致
		errors.throwConfigAdminPasswordChanged();
	}

	return user;
}



function* getAdmins(page = 1, limit = 20) {
	let result = yield utils.pagenation(Admin, page, limit, { deleted: false });
	result.rows = result.rows.map((u) => {
		delete u.password;
		return u;
	})
	return result;
}

function* addAdmin(username, password) {
	if (!username && !password) errors.throwLackParameters();
	let admin = yield Admin.findOne({ where: { username, deleted: false } });
	if (admin) errors.throwAccountIsExist();

	password = security.sign(password);
	return yield Admin.create({ username, password });
}


function* deleteAdmins(ids = []) {
	yield Admin.update({ deleted: true }, { where: { id: ids } });
}


function* updateAdminPassword(id, password) {
	if (!password) errors.throwLackParameters();
	password = security.sign(password);
	return yield Admin.update({ password }, { where: { id } });
}


module.exports = {
	signIn,
	getAdmins,
	addAdmin,
	deleteAdmins,
	updateAdminPassword
}